<?php
/* +----------------------------------------------------------------------
// | 	xaoam.com
// |	author:am
// |	gitee:https://gitee.com/xaoam/amAdmin
// |	email:hi@xaoam.com
// |	
// +----------------------------------------------------------------------*/
namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Session;
use think\captcha\Captcha;
use app\admin\validate\User as UserCheck;

class Login extends Controller {
	protected $basic;
	protected function initialize(){

			$explore = $_SERVER["HTTP_USER_AGENT"];
			if( strpos($explore,"MSIE 9.0") || strpos($explore,"MSIE 8.0") || strpos($explore,"MSIE 7.0") || strpos($explore,"MSIE 6.0") ){
					echo "当前浏览器的版本较低，请使用火狐、谷歌Chrome、360浏览器等";
					header('Content-Type:text/html; charset=utf-8');
					exit();
			}
			if(session('?user_info')){
				$this->redirect('@admin/index');
			}
			$this->basic = $this->getBasic();
	}

	public function index(){
		$this->assign('basic',$this->basic);
        return $this->fetch();
	}
	public function captcha()
	    {	ob_clean();
	        $captcha = new Captcha(app()->config('captcha_config'));
	        return $captcha->entry();    
	    }
	public function auth(){
		$data = request()->param();
        $check = new UserCheck;

        if (!$check->scene('check')->check($data)) {
			return json(['msg'=>$check->getError(),'code'=>1]);
        }
		if($this->basic['code'] == 1)
		{  		$captcha = new Captcha();
			if(!$captcha->check($data['captcha'])){
				return json(['msg'=>'验证码错误','code'=>1]);
			}
		}
		$salt = Db::name('user')->where('username',$data['username'])->value('salt');
		$where = [
			'username'	=>	$data['username'],
			'passwd'=>	getHash($data['passwd'],$salt),
			'salt'	=>	$salt
			];
			$res = Db::name('user')->where($where)->field('passwd,salt',true)->find();
			if($res){
					if($res['admin']){
							$res['login_time'] = time();
								app('session')->set('user_info',$res);
								$d['last_login_time'] = date("Y-m-d H:i:s");
								$d['id']	= $res['id'];
								Db::name('user')->update($d);
								return json(['msg'=>'登陆后台中..','code'=>200,'url'=>url('@admin/index')]);
					}else{
						return json(['msg'=>'登陆用户中心中..','code'=>200,'url'=>url('@index/index')]);
					}			
			}else{
				return json(['msg'=>'用户名或密码错误','code'=>1]);
				}
				
	}
	public function tools(){
		$result = openssl_encrypt('123456', 'DES-ECB', 'xaoam', 0);
		var_dump($result);
		var_dump(openssl_decrypt('9ANJZI1ELEs=', 'DES-ECB', '1Ha8oZE4WU', 0));
	}
	protected function getBasic(){
		return Db::name('basic')->find();
	}
}
